<template>
  <div class="home">
    <div class="wrap">
      <ul class="nav">
        <li
          v-for="(item, index) in cate"
          :key="item._id"
          @click="change(item._id, index)"
          :class="{ active: index == flag }"
        >
          {{ item.title }}
        </li>
      </ul>
    </div>
    <ul class="con">
      <li v-for="item in result" :key="item._id" @click="gotodetail(item)">
        <img :src="item.pic" alt="" />
        <h5>{{ item.title }}</h5>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cate: [],
      //商品分类数据
      list: [],
      //所有的商品数据
      result: [],
      //筛选出来的商品数据
      flag: 0,
      //点击变色 保存当前点击的分类的下标
    };
  },
  created() {
    this.getcate();
    this.getlist();
    //进入页面获取分类和列表数据
  },
  methods: {
    getcate() {
      this.$axios.get("fenlei.json").then((res) => {
        console.log(res);
        this.cate = res.data.result;
      });
    },
    //获取分类数据
    getlist() {
      this.$axios.get("list.json").then((res) => {
        console.log(res);
        this.list = res.data.result;
        this.change("59f1e1ada1da8b15d42234e9", 0);
        //放在这里保证有了list之后才去筛选数据
      });
    },
    //获取列表数据
    change(id, index) {
      this.flag = index;
      this.result = this.list.filter((item) => {
        return item.cid == id;
      });
      //根据商品的cid进行筛选 筛选的结果保存给result
    },
    gotodetail(item) {
      this.$router.push({ path: "/detail", query: { obj: item } });
    },
  },
};
</script>
<style lang="scss" scoped>
.wrap {
  width: 100%;
  overflow: scroll;
}
.nav {
  display: flex;
  li {
    width: 100px;
    border: 1px solid #ccc;
    height: 30px;
    line-height: 30px;
    flex-shrink: 0; //flex布局中放不下的时候所有的元素会等比缩小 这个属性让元素不缩小
    text-align: center;
  }
}
.con {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;

  flex-wrap: wrap;
  li {
    width: 45%;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 30px;
    img {
      width: 100%;
      height: 200px;
    }
  }
}
.active {
  background: brown;
  color: #fff;
}
</style>
